<template>
  <el-container>
    <el-main>
      <div v-if="articles && articles.length">
        <el-card
          v-for="article in articles"
          :key="article._id"
          class="article-card"
        >
          <h2>{{ article.title }}</h2>
          <p>{{ article.preview }}</p>
          <el-button text @click="viewDetail(article._id)">阅读更多</el-button>
        </el-card>
      </div>
      <div v-else class="no-data">No data</div>
    </el-main>
  </el-container>
</template>

<script setup lang="ts">
import { ElMessage } from 'element-plus'
import { onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import axios from '../axios'
import { useAuthStore } from '../store/auth'
import { Article } from '../types/Article'

const articles = ref<Article[]>([])
const authStore = useAuthStore()
const router = useRouter()

const fetchArticles = async () => {
  try {
    const resp = await axios.get<Article[]>('articles')
    articles.value = resp.data
  } catch (error) {
    console.error('articles list Error', error)
  }
}

const viewDetail = (id: string) => {
  if (!authStore.isAuthenticated) {
    ElMessage.error('请先登录')
    return
  }

  router.push({
    name: 'NewsDetail',
    params: { id },
  })
}

onMounted(fetchArticles)
</script>

<style scoped>
.article-card {
  margin: 20px 0;
}

.no-data {
  text-align: center;
  font-size: 1.2em;
  color: #999;
}
</style>
